<template>
  <div class="container">
    <div class="app-container">
      <el-scrollbar>
        <div class="left">
          <el-input
            v-model="params.keyword"
            style="margin-bottom: 10px"
            type="text"
            prefix-icon="el-icon-search"
            size="small"
            clearable
            placeholder="输入员工姓名全员搜索"
            @clear="clear"
            @input="searchEmployee"
          />
          <!-- 树形组件 -->
          <!-- 打开展开  高亮    点击箭头 -->
          <el-tree
            ref="treeRef"
            node-key="id"
            :data="treeData"
            :props="{ label: 'name' }"
            default-expand-all
            highlight-current
            :expand-on-click-node="false"
            @current-change="nodeClick"
          />
        </div>

      </el-scrollbar>

      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'adduser'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button v-permission="'importexcel'" size="mini" @click="imExcle">excel导入</el-button>
          <el-button v-permission="'exportexcel'" size="mini" @click="exportExcel">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="tableData" border="">
          <el-table-column label="头像" prop="staffPhoto" align="center">
            <template #default="{ row }">
              <el-avatar
                v-if="row.staffPhoto"
                size="medium"
                :src="row.staffPhoto"
              />
              <span v-else class="username">{{ row.username[0] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" sortable prop="mobile" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{ row }">
              {{
                row.formOfEmployment === 1
                  ? "正式"
                  : row.formOfEmployment === 2
                    ? "非正式"
                    : "未知"
              }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column
            label="入职时间"
            sortable
            width="150px"
            prop="timeOfEntry"
          />
          <el-table-column label="操作">
            <template #default="{row}">
              <!-- query传参可以直接跳转 -->
              <!-- <el-button type="text" size="mini" @click="$router.push(`/employee/detail?id=${id}`)">查看</el-button> -->
              <!-- params传参 需要在路由规则中 /:id?     加问号是可选意思  如果不加编辑过去了添加过不去 -->
              <el-button type="text" size="mini" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="mini" @click="showAssignDialog(row.id)">角色</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="delEmployee(row.id)"
              >
                <el-button slot="reference" style="margin-left:10px" type="text" size="mini">删除</el-button>
              </el-popconfirm>
            </template>

          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          style="float: right; margin-top: 20px"
          :current-page="params.page"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="params.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 提示框 -->
    <importExcel :show-excel-dialog.sync="showExcelDialog" @reload="getEmployees" />
    <!-- 分配角色得对话框 -->
    <el-dialog title="分配角色" :visible.sync="visible">
      <el-checkbox-group v-model="checkLikt">
        <el-checkbox
          v-for=" item in roles"
          :key="item.id"
          :label="item.id"
        >
          {{ item.name }}
        </el-checkbox>

      </el-checkbox-group>
      <div style="text-align:center">
        <el-button type="primary" size="mini" @click="assginRole">确定</el-button>
        <el-button size="mini" @click="visible=false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { reqGetDepts } from '@/api/department'
import { reqGetEmployees, reqExportExcel, reqDekEmployee, reqGetEnableRoles, reqGetDetail, reqAssignRole } from '@/api/employee'
// checkPermission   直接utils引入  一定要在方法中使用method
import { translateToTreeData } from '@/utils'
import FileSaver from 'file-saver'
import importExcel from './components/import-excel'

let timer
export default {
  name: 'Employee',
  components: {
    importExcel
  },
  data() {
    return {
      treeData: [], // 树形组件的数据
      params: {
        // 获取员工列表数据的参数
        departmentId: null,
        page: 1,
        pagesize: 5,
        keyword: '',
        id: null // 员工id
      },
      total: 0, // 员工总数
      tableData: [], // 员工列表数据
      showExcelDialog: false, // 控制excel的弹层显示和隐藏
      visible: false, // 控制dialog  显示隐藏
      roles: [], // 已启用的角色列表
      checkLikt: [] // 选中的角色会被收集到这个数组中
    }
  },
  created() {
    this.getDepts()
  },
  methods: {
    // 控制按钮权限第二种方式
    // 按钮里直接调用 v-if='checkPermission('adduser')'     括号里的要和标识一致
    // :disabled='checkPermission('adduser')'  这样也可以
    // 基于权限点控制
    // 也可以抽离 utils  最好封装起来
    // checkPermission(flag) {
    //   return this.$store.getters.points.includes(flag) // true就显示false隐藏
    // },
    // utils引入在这里调用
    // checkPermission,

    // 获取部门列表
    async getDepts() {
      const res = await reqGetDepts()
      this.treeData = translateToTreeData(res.data, 0)
      // console.log(this.treeData)
      // 默认记录第一个部门的id
      this.params.departmentId = this.treeData[0].id
      // await this.$nextTick()
      // 要执行的代码
      this.$nextTick(() => {
        // 默认高亮记录的部门
        this.$refs.treeRef.setCurrentKey(this.params.departmentId)
      })
      this.getEmployees()
    },
    // 叶子节点被点击 记录部门的id
    nodeClick(data) {
      // data就是点击的部门的信息对象
      this.params.departmentId = data.id
      // 切换部门后将params.page 设置为1
      this.params.page = 1
      // 切换了部门后 再发送请求获取对应部门的员工列表
      this.getEmployees()
      console.log(this.tableData)
    },
    // 获取员工列表
    async getEmployees() {
      const {
        data: { rows, total }
      } = await reqGetEmployees(this.params)
      this.tableData = rows
      this.total = total
      console.log(this.tableData)
    },
    // 每页条数发送变化 pagesize发送变化的处理函数
    handleSizeChange(val) {
      this.params.pagesize = val
      this.getEmployees()
    },
    // 页码发生变化  page发生变化的处理函数
    handleCurrentChange(val) {
      this.params.page = val
      this.getEmployees()
    },
    // 员工搜索
    searchEmployee() {
      if (!this.params.keyword.trim()) return
      // 将params.page 设置为1  再去获取员工列表
      this.params.page = 1
      clearTimeout(timer)
      timer = setTimeout(async() => {
        await this.getEmployees()
      }, 500)
    },
    // 清空keyword获取所有员工
    clear() {
      this.params.page = 1
      this.params.departmentId = this.treeData[0].id
      this.getEmployees()
    },
    // 导出excel
    async exportExcel() {
      console.log(12)
      const blob = await reqExportExcel()
      console.log(blob)
      FileSaver.saveAs(blob, '员工信息表格.xlsx')
    },
    // 导入
    imExcle() {
      this.showExcelDialog = true
    },
    // 删除员工
    async delEmployee(id) {
      // 发送请求
      await reqDekEmployee(id)
      if (this.tableData.length === 1 && this.params.page > 1) this.params.page--
      this.getEmployees()
    },
    // 角色
    async showAssignDialog(id) {
      this.id = id
      // 获取所有启用角色
      // const res = await reqGetEnableRoles()
      // this.roles = res.data
      // 获取当前用户已有角色
      // const { data } = await reqGetDepts(id)
      // this.checkLikt =  data.roles
      // this.visible = true
      // 如果以最快的速度拿到多个并发请求的数据 一次请求多个接口  并发  上边的是累加的
      Promise.all([reqGetEnableRoles(), reqGetDetail(id)]).then(values => {
        // console.log(this.roles)
        this.roles = values[0].data
        this.checkLikt = values[1].data.roleIds
        this.visible = true
      })
    },
    // 为员工分配角色
    async assginRole() {
      await reqAssignRole(this.id, this.checkLikt)
      this.visible = false // 关闭弹窗
    }
  }
}
</script>

<style lang="scss" scoped>
 ::v-deep .el-scrollbar .el-scrollbar__wrap{
 overflow-x: hidden;

}
 ::v-deep .el-scrollbar__bar.is-horizontal{
  width: 0;
  height: 0;
}

.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
